import os
import subprocess
import sys
import threading
from rich.console import Console
from src.backend.utils.envLoader import appConfig

console = Console()

viteProcess = None  # 全局vite进程变量

def runVite():
    global viteProcess
    if not appConfig.VITE_HMR:
        return

    if os.name == 'nt':
        viteExecutable = "node_modules/.bin/vite.CMD"
    else:
        viteExecutable = "node_modules/.bin/vite"
    vitePath = os.path.join(os.getcwd(), viteExecutable)
    try:
        viteProcess = subprocess.Popen(
            [vitePath],
            stdout=sys.stdout,
            stderr=sys.stderr,
            stdin=sys.stdin,
            encoding="utf-8"
        )
        if viteProcess.stdout:
            for line in viteProcess.stdout:
                if line.startswith("INFO") and "VITE v" in line and "ready in" in line:
                    console.print(line.strip(), style="green")
                else:
                    print(line.strip())
        viteProcess.wait()
    except FileNotFoundError:
        console.print(f"Error: The specified file was not found: {vitePath}", style="red")
    except Exception as e:
        console.print(f"An error occurred while starting Vite: {e}", style="red")

def runViteInThread():
    if appConfig.VITE_HMR:
        threading.Thread(target=runVite, daemon=True).start()

async def stopVite():
    global viteProcess
    if viteProcess is not None and viteProcess.poll() is None:
        viteProcess.terminate()
        try:
            # Popen.wait() is blocking, not awaitable.
            # To avoid blocking the main async loop, it's better to run it in a thread.
            # However, for a simple shutdown sequence, a short direct wait is often acceptable.
            # For this case, we'll keep it simple.
            viteProcess.wait(timeout=5)
            console.print("Vite dev server stopped.", style="yellow")
        except subprocess.TimeoutExpired:
            viteProcess.kill()
            console.print("Vite dev server force-killed after timeout.", style="red")
    viteProcess = None 